package tvv.levelup.dao;

import org.hibernate.Session;
import tvv.levelup.model.Car;
import tvv.levelup.model.Player;
import tvv.levelup.util.HibernateUtil;

import java.util.Set;

/**
 * Created by VLAD on 29.06.2014.
 */
public class PlayerDao
{
    public void savePlayer(Player p)
    {
        Session currentSession = null;
        try{
            currentSession = HibernateUtil.getSessionFactory().getCurrentSession();
            currentSession.beginTransaction();
            currentSession.save(p);
            currentSession.getTransaction().commit();


        }catch (Exception e)
        {
            currentSession.getTransaction().rollback();
            e.printStackTrace();
        }

    }

    public void saveCar(Car c)
    {
        Session currentSession = null;
        try{
            currentSession = HibernateUtil.getSessionFactory().getCurrentSession();
            currentSession.beginTransaction();
            currentSession.save(c);
            currentSession.getTransaction().commit();


        }catch (Exception e)
        {
            currentSession.getTransaction().rollback();
            e.printStackTrace();
        }

    }

    public void addCarToPlayer(int playerId, int carId){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Player p = (Player)session.load(Player.class, playerId);
        Car c = (Car)session.load(Car.class, carId);
        p.addCar(c);
        session.getTransaction().commit();
    }

    public Set<Car> getPlayerCars(int playerId) {
        Set<Car> toSend;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Player player = (Player) session.load(Player.class, playerId);
        session.update(player);
        toSend = player.getCars();
        session.getTransaction().commit();
        return toSend;
    }
}
